<script setup lang="tsx">
import { onMounted, ref } from 'vue';
import { Icon } from '@iconify/vue';
import { exists } from '@iconify/utils';
import { collections as allIconCollections } from '@iconify-collections';

const collections = ref<Array<{ prefix: string, name: string, total?: number }>>([]);
const selectedCollection = ref<string>('');
const iconsInCollection = ref<string[]>([]);
const loading = ref(false);
const iconPreviewSize = 24; // Size for preview icons

onMounted(() => {
  try {
    // 从预处理的数据中读取所有图标集
    collections.value = Object.entries(allIconCollections)
      .map(([prefix, info]) => ({
        prefix,
        name: info.name,
        total: info.total
      }))
      .sort((a, b) => a.name.localeCompare(b.name));
    
    console.log('Loaded all icon collections:', collections.value.length);
    
  } catch (error) {
    console.error('Error initializing icon collections:', error);
    // 如果预处理数据失败，使用备用的图标集列表
    collections.value = [
      { prefix: 'ph', name: 'Phosphor Icons', total: 7481 },
      { prefix: 'mdi', name: 'Material Design Icons', total: 7479 },
      { prefix: 'lucide', name: 'Lucide Icons', total: 1441 },
      { prefix: 'carbon', name: 'Carbon Icons', total: 2141 },
      { prefix: 'ant-design', name: 'Ant Design Icons', total: 899 },
      { prefix: 'line-md', name: 'Line Material Design', total: 825 },
      { prefix: 'tdesign', name: 'TDesign Icons', total: 2944 },
      { prefix: 'ri', name: 'Remix Icons', total: 2546 },
      { prefix: 'ion', name: 'Ionicons', total: 1337 },
      { prefix: 'ep', name: 'Element Plus Icons', total: 2256 },
      { prefix: 'bi', name: 'Bootstrap Icons', total: 2043 },
      { prefix: 'fe', name: 'Feather Icons', total: 287 },
      { prefix: 'heroicons', name: 'Heroicons', total: 1862 },
      { prefix: 'tabler', name: 'Tabler Icons', total: 5375 },
      { prefix: 'simple-icons', name: 'Simple Icons', total: 2928 }
    ];
  }
});

// 加载集合中的图标
const loadIconsInCollection = (prefix: string) => {
  selectedCollection.value = prefix;
  iconsInCollection.value = [];
  loading.value = true;
  
  try {
    // 对于每个集合，我们尝试加载一些常见的图标
    // 这比尝试加载整个集合更高效且适合浏览器环境
    loadSampleIcons(prefix);
  } catch (error) {
    console.error(`Error loading icons for collection ${prefix}:`, error);
    iconsInCollection.value = [];
  } finally {
    loading.value = false;
  }
};

// 尝试加载集合中的一些示例图标
const loadSampleIcons = (prefix: string) => {
  const sampleIconNames = [
    'home', 'settings', 'user', 'search', 'menu', 'close', 'plus', 
    'trash', 'edit', 'check', 'info', 'alert', 'calendar', 'clock', 
    'bell', 'star', 'chevron-down', 'chevron-right', 'arrow-left', 'arrow-right'
  ];
  
  // 特殊处理一些集合
  const specialCollections: Record<string, string[]> = {
    'ph': ['article', 'home', 'settings', 'user', 'search', 'menu', 'x', 'plus', 'trash', 'edit'],
    'mdi': ['home', 'settings', 'user', 'search', 'menu', 'close', 'plus', 'trash-can', 'pencil'],
    'lucide': ['home', 'settings', 'user', 'search', 'menu', 'x', 'plus', 'trash-2', 'edit'],
    'ant-design': ['home', 'setting', 'user', 'search', 'menu', 'close', 'plus', 'delete', 'edit']
  };
  
  // 使用特定集合的图标或默认图标
  const iconsToTry = specialCollections[prefix] || sampleIconNames;
  const validIcons: string[] = [];
  
  // 检查图标是否存在
  iconsToTry.forEach(iconName => {
    const fullIconName = `${prefix}:${iconName}`;
    if (exists(fullIconName)) {
      validIcons.push(iconName);
    }
  });
  
  iconsInCollection.value = validIcons;
  console.log(`Found ${validIcons.length} valid icons in ${prefix}`);
};

// 检查图标是否存在
const checkIconExists = (collection: string, icon: string): boolean => {
  try {
    return exists(`${collection}:${icon}`);
  } catch {
    return false;
  }
};
</script>
<template>
  <div class="p-4">
    <h2 class="text-xl font-bold mb-4">Icon Collections</h2>
    
    <!-- Collection Search and Stats -->
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-4 gap-2">
      <div class="text-sm text-gray-600">
        Total collections: {{ collections.length }}
      </div>
      <div class="relative w-full md:w-64">
        <input 
          type="text" 
          v-model="searchTerm"
          placeholder="Search collections..."
          class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
      </div>
    </div>
    
    <!-- Collection Selection -->
    <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 mb-6">
      <div 
        v-for="item in collections" 
        :key="item.prefix" 
        class="border p-3 rounded-lg hover:bg-gray-50 transition-colors cursor-pointer"
        :class="{ 'border-green-500 bg-green-50': selectedCollection === item.prefix }"
        @click="loadIconsInCollection(item.prefix)"
      >
        <div class="flex items-center justify-between">
          <div class="font-medium">{{ item.prefix }}</div>
          <Icon 
            v-if="selectedCollection === item.prefix" 
            icon="ph:check" 
            class="text-green-500" 
            :width="16" 
            :height="16" 
          />
        </div>
        <div class="text-xs text-gray-600 mb-1">{{ item.name }}</div>
        <div class="text-xs text-blue-600">
          {{ item.total?.toLocaleString() }} icons
        </div>
      </div>
    </div>
    
    <!-- Icons Preview -->
    <div v-if="selectedCollection" class="mt-8">
      <h3 class="text-lg font-semibold mb-3">
        Icons in {{ selectedCollection }} 
        <span v-if="loading" class="text-sm font-normal text-gray-500">- Loading...</span>
      </h3>
      
      <div v-if="iconsInCollection.length > 0" class="flex flex-wrap gap-3 p-3 bg-gray-50 rounded-lg">
        <div 
          v-for="icon in iconsInCollection" 
          :key="icon" 
          class="flex flex-col items-center gap-2 p-3 border rounded-lg hover:shadow-md transition-shadow"
        >
          <Icon 
            :icon="`${selectedCollection}:${icon}`" 
            class="text-gray-700 icon-preview" 
            :width="iconPreviewSize" 
            :height="iconPreviewSize" 
          />
          <div class="text-center">
            <div class="text-xs text-gray-500 font-mono truncate max-w-[100px]">
              {{ selectedCollection }}:{{ icon }}
            </div>
          </div>
        </div>
      </div>
      
      <div v-else-if="!loading" class="p-4 bg-gray-50 rounded-lg text-gray-500 text-center">
        No icons found or failed to load icons for this collection.
      </div>
    </div>
    
    <!-- Usage Help -->
    <div class="mt-8 p-4 bg-blue-50 rounded-lg border border-blue-100">
      <h4 class="font-medium text-blue-800 mb-2">How to use these icons</h4>
      <pre class="text-sm text-gray-700 bg-white p-2 rounded overflow-x-auto">
        {{ `<Icon icon="${selectedCollection || 'collection'}:${iconsInCollection[0] || 'icon'}" />` }}
      </pre>
      <p class="text-xs text-gray-600 mt-2">Make sure you're using the Icon component from '@iconify/vue'</p>
    </div>
  </div>
</template>
<style lang="less" scoped>
.icon-preview {
  transition: transform 0.2s ease;
}
.icon-preview:hover {
  transform: scale(1.1);
}
</style>